<!--
 * @Description: 上传书籍信息
 * @Author:  zhangweigang
 * @Date: 2021-02-14 20:08:05
 * @LastEditTime: 2021-05-04 22:13:43
 * @LastEditors: zhangweigang
-->
<template>
  <div>
    <Header></Header>
    <curr-locat title="书籍上传"></curr-locat>
    <div class="contain">
      <el-form :model="ruleForm" :label-position="labelPosition" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="书籍名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="ruleForm.author"></el-input>
        </el-form-item>
        <el-form-item label="书籍类型" prop="bookCategoryId">
          <el-select v-model="ruleForm.bookCategoryId" placeholder="请选择书籍类型" @change="bookSelectCate">
            <el-option v-for="(item, index) in bookCateList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传书籍文件" prop="fileName" required>
          <el-input v-model="ruleForm.fileName" placeholder="请上传文件" style="width: 150px" :disabled="true"> </el-input>
          <el-upload style="width: 200px; display: inline; margin-left: 25px" name="bookFile" class="upload-demo" ref="upload" action="/api/bsBook/upload" :show-file-list="true" :before-upload="beforeUploadPDF">
            <el-button class="selectfile" slot="trigger" type="danger" icon="el-icon-upload2">选取文件</el-button>
            <el-button type="danger" @click="viewFile" icon="el-icon-view">预览</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="选择书籍出版日期" required>
          <el-col :span="11">
            <el-form-item prop="publicationDate">
              <el-date-picker type="datetime" placeholder="选择日期" v-model="ruleForm.publicationDate" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="选择书籍封面" prop="coverUrl" required>
          <el-upload class="switch-block" name="coverFile" action="/api/bsBook/upload" list-type="picture-card" accept="image/png, image/gif, image/jpg, image/jpeg" :limit="1" :auto-upload="false" :file-list="coverFileList" :on-change="uploadCoverChange" :on-preview="handlePicture" :on-remove="handleRemove" :on-exceed="overFile">
            <el-button slot="trigger" size="mini" type="danger">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过10MB
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="选择版权证件" prop="copyrightUrl" required>
          <el-upload class="switch-block" name="copyrightFile" action="/api/bsBook/upload" accept="image/png, image/gif, image/jpg, image/jpeg" :limit="1" list-type="picture-card" :on-preview="handlePicture" :on-remove="handleRemove" :on-change="uploadCopyChange" :on-exceed="overFile" :auto-upload="false" :file-list="copyFileList">
            <el-button slot="trigger" size="mini" type="danger">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过10MB
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
        <!--大图弹出框-->
        <el-dialog :visible.sync="dialogVisible" :modal="false" size="full" title="查看大图片">
          <img width="100%" :src="ruleForm.lookImageUrl" alt />
        </el-dialog>
      </el-form>
    </div>
    <Footer></Footer>
  </div>
</template>

<script>
import { uploadBookBaseInfo, getCateInfo } from '../../network/product';
export default {
  data() {
    return {
      labelPosition: 'top',
      coverFileList: [], // 书籍封面图
      copyFileList: [], // 版权证书图
      // 书籍信息表单
      ruleForm: {
        name: '', // 书籍名称
        author: '', // 作者
        bookCategoryId: '', // 书籍分类 字段
        publicationDate: '', // 出版日期
        coverUrl: '', // 书籍封面图
        copyrightUrl: '', // 版权图片
        // pdf 文件上传
        file: null, //
        fileName: '', // 书籍文件名称
        lookImageUrl: '' // 查看大图片路径
      },
      fileData: null, // 书籍文件预览
      bookFileData: null, // 书籍上传文件
      bsFileCover: {}, // 书籍封面文件
      bsFileCopy: {}, // 书籍版权文件
      rules: {
        name: [
          { required: true, message: '请输入书籍名称', trigger: 'blur' },
          {
            min: 1,
            max: 12,
            message: '长度在 1 到 12 个字符',
            trigger: 'blur'
          }
        ],
        author: [
          { required: true, message: '请输入作者名称', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
        ],
        bookCategoryId: [{ required: true, message: '请选择书籍类型', trigger: 'change' }],
        fileName: [{ required: true, message: '请先上传书籍', trigger: 'change' }],
        publicationDate: [
          {
            type: 'date',
            required: true,
            message: '请选择书籍出版日期',
            trigger: 'change'
          }
        ],
        coverUrl: [
          {
            required: true,
            message: '请上传图书封面',
            trigger: ['blur', 'change']
          }
        ],
        copyrightUrl: [
          {
            required: true,
            message: '请上传图书版权证书',
            trigger: ['blur', 'change']
          }
        ]
      },
      //图片查看框 隐藏或者显示
      dialogVisible: false,
      // 书籍分类列表
      bookCateList: []
    };
  },
  mounted() {
    // 获取书籍分类
    this.getAllCateData();
  },
  methods: {
    // 获取分类
    getAllCateData() {
      getCateInfo().then((res) => {
        if (res.data.code === 0 && res.status === 200) {
          res.data.data.map((item) => {
            this.bookCateList.push(item);
          });
          console.log(res.data.data, '书籍分类');
        } else {
          this.$message({
            showClose: true,
            message: '书籍分类获取失败，请联系管理员！',
            type: 'error',
            duration: 4000
          });
        }
      });
    },
    // select改变时触发
    bookSelectCate(id) {
      this.ruleForm.bookCategoryId = id;
      console.log(id, '类型id');
    },
    /**
     * 获取时间
     * @time 中国标准时间
     * @return 返回时间 格式 年-月-日 小时:分钟:毫秒
     */
    getYMD(time) {
      console.log(time);
      let date = new Date(time);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      m = m < 10 ? '0' + m : m;
      let d = date.getDate();
      d = d < 10 ? '0' + d : d;
      let h = date.getHours();
      h = h < 10 ? '0' + h : h;
      let M = date.getMinutes();
      M = M < 10 ? '0' + M : M;
      let s = date.getSeconds();
      s = s < 10 ? '0' + s : s;
      let dateTime = y + '-' + m + '-' + d + ' ' + h + ':' + M + ':' + s;
      return dateTime;
    },
    /**
     * 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
     * 获取书籍封面图片文件
     * @file
     * @fileList
     */
    uploadCoverChange(file, fileList) {
      console.log(file, '====', fileList);
      const isIMAGE = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png' || file.raw.type === 'image/jpg' || file.raw.type === 'image/gif';
      const isLt5M = file.size / 1024 / 1024 < 10;
      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 10MB!');
        return false;
      }
      this.ruleForm.coverUrl = file.url;
      this.bsFileCover['coverFile'] = fileList;
    },
    /**
     * 获取版权图片文件
     * @file
     * @fileList
     */
    uploadCopyChange(file, fileList) {
      console.log(file, '====', fileList);
      const isIMAGE = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png' || file.raw.type === 'image/jpg' || file.raw.type === 'image/gif';
      const isLt5M = file.size / 1024 / 1024 < 10;
      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 10MB!');
        return false;
      }
      this.ruleForm.copyrightUrl = file.url;
      this.bsFileCopy['copyrightFile'] = fileList;
    },
    //文件超出提示
    overFile(files, fileList) {
      console.log(files, '文件');
      console.log(fileList, '文件列表');
      if (files.length >= 1) {
        this.$message({
          showClose: true,
          message: '只能上传一张图片！',
          type: 'error',
          duration: 4000
        });
      }
    },
    // PDF 上传之前钩子调用
    beforeUploadPDF(file) {
      const extension = file.name.split('.').slice(-1) == 'pdf';
      if (!extension) {
        this.$message.warning('上传模板只能是pdf格式!');
        return;
      }
      let reader = new FileReader();
      reader.readAsDataURL(file);
      let that = this;
      reader.onload = function() {
        that.fileData = reader.result;
      };

      this.ruleForm.file = file;
      this.ruleForm.fileName = file.name;
      this.bookFileData = file;
      return false; // 返回false不会自动上传
    },
    //预览 PDF 文件，这里用的是打开新窗口用浏览器查看 PDF
    viewFile() {
      if (this.fileData == null) {
        this.$message.warning('请先上传PDF文件');
        return false;
      }
      var win = window.open();
      win.document.write('<body style="margin:0px;"><object data="' + this.fileData + '" type="application/pdf" width="100%" height="100%"><iframe src="' + this.fileData + '" scrolling="no" width="100%" height="100%" frameborder="0" ></iframe></object></body>');
    },
    // 表单提交
    async submitForm(formName) {
      let submitFormData = new FormData();
      submitFormData.append('bookFile', this.bookFileData); // 书籍文件
      let tempBookBaseInfo = {
        content: '书籍内容'
      };
      // 书籍封面文件
      Object.entries(this.bsFileCover).forEach((file) => {
        console.log(file, '123');
        file[1].forEach((item) => {
          // 下面的 "coverFile"，对应后端需要接收的name，这样对图片和文件做一个区分，name为images为图片
          submitFormData.append('coverFile', item.raw);
        });
      });
      // 版权文件
      Object.entries(this.bsFileCopy).forEach((file) => {
        console.log(file, '456');
        file[1].forEach((item) => {
          submitFormData.append('copyrightFile', item.raw);
        });
      });
      submitFormData.append('name', this.ruleForm.name); // 书籍名称
      submitFormData.append('author', this.ruleForm.author); // 书籍作者
      submitFormData.append('content', tempBookBaseInfo.content);
      submitFormData.append('bookCategoryId', this.ruleForm.bookCategoryId); // 书籍分类Id
      submitFormData.append('publicationDate', this.getYMD(this.ruleForm.publicationDate)); // 出版日期
      submitFormData.forEach((element) => {
        console.log(element, '上传参数');
      });
      // 下一步提交数据，上传书籍
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 书籍基础信息
          uploadBookBaseInfo(submitFormData).then((res) => {
            console.log(res, '提交返回结果');
            if (res.data.code === 0) {
              this.$message({
                showClose: true,
                message: '上传成功！请等待管理员审核！',
                type: 'success',
                duration: 4000
              });
              this.$router.push('/sharebook');
            } else {
              this.$message({
                showClose: true,
                message: '上传失败，请联系管理员！',
                type: 'error',
                duration: 4000
              });
            }
          });
        } else {
          this.$message({
            showClose: true,
            message: '请重新检查数据填写是否有遗漏！',
            type: 'error',
            duration: 4000
          });
          return false;
        }
      });
    },
    //表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 大图处理
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePicture(file) {
      this.ruleForm.lookImageUrl = file.url;
      this.dialogVisible = true;
    }
  }
};
</script>

<style lang="less" scoped>
.switch-block {
  display: inline-block;
}
div[class^='upload'] {
  margin: 10px 0;
  font-size: 14px;
  color: #606266;
}
.upload-image {
  span {
    display: inline-block;
    font-size: 10px;
    color: red;
    padding-left: 10px;
  }
}
.selectfile {
  margin-right: 20px;
}
.el-upload__tip {
  color: red;
}
</style>
